package model;

import java.io.Serializable;
import java.util.List;
import org.codeforsurvive.utils.MySqlUtil;
import org.hibernate.Query;
import org.hibernate.Session;

/**
 *
 * @author Rohmad Raharjo
 */
public class BaseModel implements Serializable {

    protected String tableName;

    public BaseModel() {

    }

    public void save(Object item) {
        Session session = MySqlUtil.getSessionFactory().openSession();
        session.saveOrUpdate(item);
        session.flush();
        session.close();
    }

    public List createQuery(String query) {
        List result = null;
        Session session = MySqlUtil.getSessionFactory().openSession();
        result = session.createQuery(query).list();
        session.close();

        return result;
    }

    public List select() {
        List result = null;
        Session session = MySqlUtil.getSessionFactory().openSession();
        result = session.createQuery("from " + tableName).list();
        session.close();

        return result;

    }

    public List select(int limit) {
        List result = null;
        Session session = MySqlUtil.getSessionFactory().openSession();
        Query query = session.createQuery("from " + tableName);
        query.setMaxResults(limit);
        result = query.list();
        session.close();

        return result;
    }

    public List select(int start, int limit) {
        List result = null;
        Session session = MySqlUtil.getSessionFactory().openSession();
        Query query = session.createQuery("from " + tableName);
        query.setFirstResult(start);
        query.setMaxResults(limit);
        result = query.list();
        session.close();

        return result;
    }
    
    public Object getById(String id)
    {
        List result = null;
        Session session = MySqlUtil.getSessionFactory().openSession();
        Query query = session.createQuery("from " + tableName + " where id = " + id);
        result = query.list();
        session.close();

        return (result.size() > 0) ? result.get(0) : null;        
    }
    
    public List getByColumn(String columnName, String value)
    {
        List result = null;
        Session session = MySqlUtil.getSessionFactory().openSession();
        Query query = session.createQuery("from " + tableName + " where " + columnName + " = '" + value + "'");
        result = query.list();
        session.close();

        return result;
    }
    
    
    
    

}
